﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CRMExam.Models;
using Microsoft.AspNet.Identity;
using CRMExam.Database;
using System.Collections;

namespace CRMExam.Controllers
{
    [Authorize]
    public class MeetingController : Controller
    {

        CRMExam1Entities db = new CRMExam1Entities();

        public ActionResult Create()
        {
            MeetingViewModel model = new MeetingViewModel();

            var userId = User.Identity.GetUserId();

            List<AspNetUser> users = new List<AspNetUser>();
            AspNetUser a = new AspNetUser { Id = Guid.NewGuid().ToString() };
            users.Add(a);

            var dvbh = db.AspNetUsers.Where(u => u.Id != userId);

            model.Receivers = new SelectList(db.AspNetUsers.Where(u => u.Id != userId), "Id", "UserName");
            model.Contacts = new SelectList(db.Contacts.Where(c => c.AspNetUsersId == userId), "Id", "Name");
            model.SelectedReceivers = new SelectList(users, "Id", "UserName");

            return View(model);
        }

        [HttpPost]
        public ActionResult Create(MeetingViewModel model)
        {
            var currentUser = User.Identity.GetUserId();

            var newMeetingGuid = Guid.NewGuid();

            var meeting = new Meeting
            {
                Id = newMeetingGuid,
                ContactId = model.ContactId,
                Created = model.Created,
                Description = model.Description,
                StartTime = model.StartTime,
                EndTime = model.EndTime,
                Location = model.Location,
                IsTask = model.IsTask,
                Priority = model.Priority,
                Status = model.Status,
                Subject = model.Subject,
                OwnerId = currentUser
            };

            db.Meetings.Add(meeting);
            

            AspNetUserMeeting aspNetUserMeeting = new AspNetUserMeeting();
            aspNetUserMeeting.Id = Guid.NewGuid();
            aspNetUserMeeting.AspNetUserId = currentUser;
            aspNetUserMeeting.MeetingId = newMeetingGuid;
            aspNetUserMeeting.OwnerId = currentUser;
            aspNetUserMeeting.HasAccept = false;
            db.AspNetUserMeetings.Add(aspNetUserMeeting);
            

            if (model.IsTask == false)
            {
                if (!string.IsNullOrEmpty(model.Selected))
                {
                    string[] ids = model.Selected.Remove(0, 1).Split(',');

                    foreach (string id in ids)
                    {
                        AspNetUserMeeting a = new AspNetUserMeeting();
                        a.Id = Guid.NewGuid();
                        a.AspNetUserId = id;
                        a.MeetingId = newMeetingGuid;
                        a.OwnerId = currentUser;
                        a.HasAccept = false;
                        db.AspNetUserMeetings.Add(a);                       
                    }
                }

                if (!string.IsNullOrEmpty(model.SelectedContacts))
                {
                    string[] ids = model.SelectedContacts.Remove(0, 1).Split(',');

                    foreach (string id in ids)
                    {
                        ContactMeeting a = new ContactMeeting();
                        a.Id = Guid.NewGuid();
                        a.ContactId = Guid.Parse(id);
                        a.MeetingId = newMeetingGuid;
                        db.ContactMeetings.Add(a);                       
                    }
                }
            }

            db.SaveChanges();

            return RedirectToAction("Create");
        }

        public ActionResult Details(Guid id)
        {
            var currentUser = User.Identity.GetUserId();

            var meeting = db.Meetings.FirstOrDefault(i => i.Id == id);


            //Meeting
            List<AspNetUserMeeting> userMeetings = db.AspNetUserMeetings.Where(m => m.MeetingId == id).ToList(); 

            List<AspNetUser> users = new List<AspNetUser>();

            foreach (var userMeeting in userMeetings)
            {
                if (userMeeting.AspNetUserId != currentUser)
                {
                    users.Add(userMeeting.AspNetUser);
                }
            }

            //Contacts
            List<ContactMeeting> userContacts = db.ContactMeetings.Where(m => m.MeetingId == id).ToList();

            List<Contact> contacts = new List<Contact>();

            foreach (var userContact in userContacts)
            {
                    contacts.Add(userContact.Contact);                
            }



            var taskOrMeeting = string.Empty;

            if (meeting.IsTask == true)
            {
                taskOrMeeting = "Task";
            }
            else if (meeting.IsTask == false)
            {
                taskOrMeeting = "Meeting";
            }

            
            DetailsViewModel model = new DetailsViewModel
            {
                IsTask = taskOrMeeting,
                StartDate = ((DateTime)meeting.StartTime).ToShortDateString(),
                StartTime = ((DateTime)meeting.StartTime).ToShortTimeString(),
                EndDate = ((DateTime)meeting.EndTime).ToShortDateString(),
                EndTime = ((DateTime)meeting.EndTime).ToShortTimeString(),
                Subject = meeting.Subject,
                Id = meeting.Id,
                Users = new SelectList(users.Where(u => u.Id != currentUser), "Id", "UserName"),
                Contacts = new SelectList(contacts.Where(u => u.AspNetUsersId == currentUser), "Id", "Name")

            };

            return View(model);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}